package com.example.beat_x3.Fragments;

import android.annotation.SuppressLint;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.beat_x3.Adapter.SendersAdapter;
import com.example.beat_x3.Client.GetResult;
import com.example.beat_x3.R;


import java.util.ArrayList;

import Entity.Inf;

public class ContactFragment extends MyFragment {
    RecyclerView recyclerView;
    public SendersAdapter sendersAdapter;
    private final Handler myHandler = new Handler(Looper.getMainLooper()) {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void handleMessage(Message msg) {
            sendersAdapter.notifyDataSetChanged();
        }
    };

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_contacts, null);
        recyclerView = view.findViewById(R.id.contact_senders);
        sendersAdapter = new SendersAdapter();
        recyclerView.setAdapter(sendersAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(Inf.context));
        sendersAdapter.setOnItemClickListener(new SendersAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String studentAccount) {
                if (Inf.contacts.containsKey(studentAccount)) {
                    changeFragment(Inf.contacts.get(studentAccount));
                } else {
                    Inf.chatFragment = new ChatFragment(studentAccount);
                    Inf.contacts.put(studentAccount, Inf.chatFragment);
                    changeFragment(Inf.chatFragment);
                }
            }
        });
        view.findViewById(R.id.contacts_backbutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeFragment(Inf.centerFragment);
            }
        });
        new ContactThread().start();
        return view;
    }

    class ContactThread extends Thread {
        @Override
        public void run() {
            ArrayList<String> res = GetResult.QuerySenders(Inf.stuInf.StudentAccount);
            if (res != null) {
                sendersAdapter.senders = res;
                myHandler.sendEmptyMessage(0);
            }
        }
    }

}
